// 利用 Multer 中间件实现图片上传功能，并将图片路径存储在
// 数据库中。
const multer = require("multer");
const express = require("express");
const app = express();
const mysql = require("mysql");
const db = mysql.createPool({
  host: "127.0.0.1",
  database: "node",
  user: "root",
  password: "root",
});
const multerConfig = multer({
  storage: multer.diskStorage({
    destination: "public",
    filename(req, file, cb) {
      const fileFormat = file.originalname.split(".");
      cb(null, Date.now() + "." + fileFormat.at(-1));
    },
  }),
  limits: {
    fileSize: 1024 * 1024 * 5,
  },
});
app.use("/img", express.static("public"));
// 图片上传
app.post("/post", multerConfig.single("file"), (req, res) => {
  res.send({
    code: 0,
    msg: "成功",
    data: req.file.filename,
  });
});
// 启动
app.listen(3000, () => {
  console.log("项目启动了");
});
